package com.dhecp.project.business.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.dhecp.common.annotation.Log;
import com.dhecp.common.annotation.RepeatSubmit;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.core.page.TableDataInfo;
import com.dhecp.common.enums.BusinessType;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.ModuleTable;
import com.dhecp.core.layui.GridColumnsPropertyModel;
import com.dhecp.framework.web.service.BaseInfoSimpleService;
import com.dhecp.project.base.domain.BaseInfo;
import com.dhecp.project.base.service.BaseInfoService;
import com.dhecp.project.business.domain.LogisticsMmodeGrads;
import com.dhecp.project.business.domain.LogsticsPattern;
import com.dhecp.project.business.domain.LogsticsPatternDetails;
import com.dhecp.project.business.mapper.LogsticsPatternDetailsMapper;
import com.dhecp.project.business.service.LogsticsPatternService;
import com.dhecp.project.common.controller.BaseModuleController;
import com.dhecp.project.logstics.mapper.LogsticsMmodeGradsMapper;
import com.dhecp.project.system.domain.SysDictionaryForPageField;
import com.dhecp.project.system.service.SysDictionaryForFieldService;

/**
 * 物流名称
 * @Author fxz
 * @Date 2022/9/21
 */
@Controller
@RequestMapping("/business/logsticspattern")
public class LogsticsPatternController extends BaseModuleController {

    private String prefix = "business/logsticspattern";
    private String moduleTable = ModuleTable.LOGSTICS_PATTERN;
    private String moduleTable2 = ModuleTable.LOGSTICS_PATTERN_DETAILS;
    private String moduleTable3 = ModuleTable.LOGISTICS_MMODE_GRADS;

    @Autowired
    private GridColumnsPropertyModel gridColumnsPropertyModel;

    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;

    @Autowired
    private LogsticsPatternService logsticsPatternService;

    @Autowired
    private LogsticsPatternDetailsMapper logsticsPatternDetailsMapper;


    @Autowired
    private BaseInfoSimpleService baseInfoSimpleService;

    @Autowired
    private BaseInfoService baseInfoService;

    @Autowired
    private LogsticsMmodeGradsMapper logsticsMmodeGradsMapper;

    /**
     *@Description: 打开查询列表页
     *@Param: [params]
     *@return: org.springframework.web.servlet.ModelAndView
     *@Author: fxz
     *@date: 2022/9/21
     */
    @RequiresPermissions("business:logsticspattern:view")
    @GetMapping()
    public ModelAndView view(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        params.put("entity", new LogsticsPattern()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
        params.put("prefix","business/logsticspattern/logsticspattern"); //页面路径
        params.put("toolBarWidth", 80);
        params.put("checkBox", "yes");

        ModelAndView mv = this.openListPage(params);
        mv.addObject("business", "logsticspattern");
//        mv.addObject("gridColumns", gridColumnsPropertyModel.queryGridColumnsPropertyModel(params));
        return mv;
    }

    /**
     *@Description: 查询页 列表数据
     * @Author: Jason
     * @date: 2022-09-02 11:41
     */
    @RequiresPermissions("business:logsticspattern:list")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        List<LogsticsPattern> list = new ArrayList<LogsticsPattern>();
        try {
            list = logsticsPatternService.queryList(params);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());
        }
        return getDataTable(list);
    }

    /**
     * 打开物流名称新增页
     * @Author: fxz
     * @date: 2022-09-21 11:41
     */
    @RequiresPermissions("business:logsticspattern:add")
    @GetMapping("/add")
    public ModelAndView add(@RequestParam Map<String, Object> params) throws Exception {
        params.put("moduleTable", moduleTable);
        params.put("entity", new LogsticsPattern()); //用于获取实体属性名取代对应字典字段名，解决大小写敏感问题
        ModelAndView mv = this.getModelAndView();
        AjaxResult ajaxResult = new AjaxResult();
        List<SysDictionaryForPageField> dicFieldsList = new ArrayList<SysDictionaryForPageField>(); //字段字典
        List<Object> fieldsList = new ArrayList<Object>(); 			//生成控件的字段和属性
        List<Object> fieldsHiddenList = new ArrayList<Object>(); 	//隐藏的字段和属性
        Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
        try{
            //查询数据字典
            dictionaryForFieldMap = dictionaryForFieldService.queryFieldAttributesMap(params);
            if (dictionaryForFieldMap.isEmpty()){
                ajaxResult = AjaxResult.error("未获取到字段属性。");
            }else{
                ajaxResult = AjaxResult.success("数据获取成功。");
            }

            params.put("getFieldAttributesType", "pagenotingrid"); 	//非表格字段
            dicFieldsList = dictionaryForFieldService.queryFieldAttributesList(params);
            LogsticsPattern logsticsPattern = new LogsticsPattern();
            logsticsPattern.setStateShareTicket("是");
            logsticsPattern.setDeletedtext("启用");
            logsticsPattern.setLogisticsType("物流");
            logsticsPattern.setNameLogsticsClearance("包税");
            logsticsPattern.setLogsticsTimeLimit("0");
            logsticsPattern.setWeightTranFrom(BigDecimal.ZERO);
            logsticsPattern.setWeightCalBySingle(BigDecimal.ZERO);
            logsticsPattern.setCoefficientWeight("0");
            logsticsPattern.setNumFreeProName(5);
            logsticsPattern.setNumMaxProName(15);
            logsticsPattern.setPriceProNamePerOne(BigDecimal.ZERO);
            logsticsPattern.setPriceClearanceOpe(BigDecimal.ZERO);
            logsticsPattern.setSinglePassCrane(BigDecimal.ZERO);
            logsticsPattern.setPriceSingleBoxReq(new BigDecimal(99999));
            logsticsPattern.setPriceSingleBoxReqZd(new BigDecimal(0));
            logsticsPattern.setWarehouseAddress("福州仓");
            if (dicFieldsList.isEmpty()){
                ajaxResult = AjaxResult.error("未获取到字段属性。");
            }else{
                for (SysDictionaryForPageField dicFields : dicFieldsList){
                    Map<String, Object> fieldsListMap = TypeUtils.entityToMap(dicFields);
                    fieldsListMap.put("fieldContent", TypeUtils.entityToMap(logsticsPattern).get(fieldsListMap.get("fields")));

                    if (fieldsListMap.get("fieldFrontType") == null){
                        fieldsListMap.put("fieldFrontType", "t_text");
                    }

                    //如果有下拉控件，则根据配置获取对应下拉待选内容
                    List<BaseInfo> dropdownList = new ArrayList<BaseInfo>();
                    String fieldFrontType = dicFields.getFieldFrontType();
                    String fieldSearchType = dicFields.getFieldSearchType();
                    String fieldFrontSave = dicFields.getFieldFrontSave();
                    String fieldFrontShow = dicFields.getFieldFrontShow();
                    if (fieldFrontType != null && fieldFrontType.toLowerCase().startsWith("t_dropdown")){
                        if (fieldSearchType != null && !"".equals(fieldSearchType)){
                            if (fieldFrontSave == null || "".equals(fieldFrontSave)){
                                fieldFrontSave = "vid";
                            }
                            if (fieldFrontShow == null || "".equals(fieldFrontShow)){
                                fieldFrontShow = "vname";
                            }
                            dropdownList = baseInfoSimpleService.getDropdownData(fieldSearchType,fieldFrontSave,fieldFrontShow);
                        }
                    }
                    fieldsListMap.put("dropdownList", dropdownList);
                    if ((Integer)fieldsListMap.get("fieldFrontTop") == 1){	//显示的字段
                        fieldsList.add(TypeUtils.mapToJson(fieldsListMap));
                    }else {	//隐藏的字段
                        fieldsHiddenList.add(TypeUtils.mapToJson(fieldsListMap));
                    }
                }
            }
        }
        catch(Exception e){
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        params.put("moduleTable", moduleTable2);
        params.put("entity", new LogsticsPatternDetails()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
        params.put("readOnly", false);//生成列是否可编辑
        params.put("toolBarWidth", 0);//操作区
        params.put("checkBox", "yes");
        params.put("getFieldAttributesType", "pageingrid");//pageingrid：网格字段
        Map<String, Object> params1 = new HashMap<String, Object>();
        params1.put("vtype", "spcz");
        params1.put("moduleTable", "TB_baseinfo_spcz");
        List<BaseInfo> list  = baseInfoService.queryBaseInfoList(params1);
        List<LogsticsPatternDetails> logsticsPatternDetailsList = new ArrayList<>();
        LogsticsPatternDetails logsticsPatternDetails;
        for (BaseInfo baseInfo : list){
            if (baseInfo.getBdeletedtext().equals("否")) {
                logsticsPatternDetails = new LogsticsPatternDetails();
                logsticsPatternDetails.setMaterialName(baseInfo.getVname());
                logsticsPatternDetails.setMaterialCost(BigDecimal.ZERO);
                logsticsPatternDetailsList.add(logsticsPatternDetails);
            }
        }
        mv.addObject("listData1", logsticsPatternDetailsList);
        mv.addObject("gridColumns", gridColumnsPropertyModel.queryGridColumnsPropertyModel(params));
        params.put("moduleTable", moduleTable3);
        params.put("entity", new LogisticsMmodeGrads());
        params.put("toolBarWidth", 0);//操作
        params.put("checkBox", "yes");
        params.put("getFieldAttributesType", "pageingrid");//pageingrid：网格字段// 区
        Map<String, Object> stringObjectMap = gridColumnsPropertyModel.queryGridColumnsPropertyModel(params);
        mv.addObject("gridColumnsZJ", stringObjectMap);
        mv.addObject("gridColumnsJZ", stringObjectMap);
        mv.addObject("enableEdit", 1); //当前页面是否可编辑（0：不可编辑，1：可编辑）
        mv.addObject("pageType","add"); //页面类型：新增（add）、修改（edit）
        mv.addObject("fields", TypeUtils.mapToJson(dictionaryForFieldMap)); //各字段及属性
        mv.addObject("fieldsList", fieldsList);				//显示的字段
        mv.addObject("fieldsHiddenList", fieldsHiddenList);	//隐藏的字段
        mv.addObject("ajaxResult", ajaxResult);
        mv.setViewName(prefix + "/logsticspattern_add");
        return mv;
    }

    /**
     * 新增物流名称
     * @author fxz
     * @date: 2022-09-22 10:08
     */
    @Log(title = "新增物流名称", businessType = BusinessType.INSERT)
    @RequiresPermissions("business:logsticspattern:add")
    @PostMapping("/addpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult addpost(@RequestParam Map<String, Object> params){

        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= logsticsPatternService.insertLogsticsServer(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }


    /**
     * 打开物流名称修改页
     * @Author: fxz
     * @date: 2022-09-22 19:00
     */
    @RequiresPermissions("business:logsticspattern:edit")
    @GetMapping("/edit")
    public ModelAndView edit(@RequestParam Map<String, Object> params){

        params.put("moduleTable", moduleTable);
        params.put("entity", new LogsticsPattern()); //用于获取实体属性名取代对应字典字段名，解决大小写敏感问题
        ModelAndView mv = this.getModelAndView();
        AjaxResult ajaxResult = new AjaxResult();
        List<SysDictionaryForPageField> dicFieldsList = new ArrayList<SysDictionaryForPageField>();
        List<Object> fieldsList = new ArrayList<Object>();
        List<Object> fieldsHiddenList = new ArrayList<Object>(); 			//隐藏的字段和属性
        List<String> fieldRequiredList = new ArrayList<String>();
        try{
            params.put("getFieldAttributesType", "pagenotingrid"); 	//非表格字段
            dicFieldsList = dictionaryForFieldService.queryFieldAttributesList(params);
            if (dicFieldsList.isEmpty()){
                ajaxResult = AjaxResult.error("未获取到字段属性。");
            }else{
                LogsticsPattern logsticsPattern = logsticsPatternService.queryFirstByGuid(params);
                if (logsticsPattern == null){
                    ajaxResult = AjaxResult.error("没有查到物流名称[" + params.get("Guid").toString() + "]的信息。");
                }else{
                    logsticsPattern.setStateShareTicket(logsticsPattern.getStateShareTicket().equals("1")? "是":"否");
                    logsticsPattern.setDeletedtext(logsticsPattern.getDeletedtext().equals("1")? "启用":"禁用");
                    //获取物流名称详情
                    Map<String, Object> params2 = new HashMap<String, Object>();
                    params2.put("code",logsticsPattern.getCode());
                    params2.put("logisticsMmodeGuid",logsticsPattern.getGuid());
                    List<LogsticsPatternDetails> logsticsPatternDetailsList = logsticsPatternDetailsMapper.findLogsticsPatternDetails(params2);
                    //获取物流方式梯度
                    List<LogisticsMmodeGrads> logisticsMmodeGradList = logsticsMmodeGradsMapper.findLogisticsMmodeGrads(params2);
                    List<LogisticsMmodeGrads> logisticsMmodeGrads  = logisticsMmodeGradList.stream().filter(logisticsMmodeGrads1 ->
                            "WLMC".equals(logisticsMmodeGrads1.getType())).collect(Collectors.toList());
                    List<LogisticsMmodeGrads> logisticsMmodeInfoItems  = logisticsMmodeGradList.stream().filter(logisticsMmodeGrads1 ->
                            "WLMCTDJZ".equals(logisticsMmodeGrads1.getType())).collect(Collectors.toList());
                    ajaxResult = AjaxResult.success("数据获取成功。");
                    mv.addObject("logsticsPattern",logsticsPattern);
                    mv.addObject("logsticsPatternDetails",logsticsPatternDetailsList);
                    mv.addObject("logisticsMmodeGrads",logisticsMmodeGrads);
                    mv.addObject("logisticsMmodeInfoItems",logisticsMmodeInfoItems);
                    for (SysDictionaryForPageField dicFields : dicFieldsList){
                        Map<String, Object> fieldsListMap = TypeUtils.entityToMap(dicFields);
                        fieldsListMap.put("fieldContent", TypeUtils.entityToMap(logsticsPattern).get(fieldsListMap.get("fields")));

                        //如果有下拉控件，则根据配置获取对应下拉待选内容
                        List<BaseInfo> dropdownList = new ArrayList<BaseInfo>();
                        String fieldFrontType = dicFields.getFieldFrontType();
                        String fieldSearchType = dicFields.getFieldSearchType();
                        String fieldFrontSave = dicFields.getFieldFrontSave();
                        String fieldFrontShow = dicFields.getFieldFrontShow();
                        if (fieldFrontType != null && fieldFrontType.toLowerCase().startsWith("t_dropdown")){
                            if (fieldSearchType != null && !"".equals(fieldSearchType)){
                                if (fieldFrontSave == null || "".equals(fieldFrontSave)){
                                    fieldFrontSave = "vid";
                                }
                                if (fieldFrontShow == null || "".equals(fieldFrontShow)){
                                    fieldFrontShow = "vname";
                                }
                                dropdownList = baseInfoSimpleService.getDropdownData(fieldSearchType,fieldFrontSave,fieldFrontShow);
                            }
                        }
                        fieldsListMap.put("dropdownList", dropdownList);

                        if ((Integer)fieldsListMap.get("fieldFrontTop") == 1){ //显示的表头
                            fieldsList.add(TypeUtils.mapToJson(fieldsListMap));
                        }else{ //隐藏的表头
                            fieldsHiddenList.add(TypeUtils.mapToJson(fieldsListMap));
                        }
                        if (dicFields.getFieldFrontRequired() != null && dicFields.getFieldFrontRequired()){
                            fieldRequiredList.add(dicFields.getFields());
                        }
                    }
                }
            }
        }
        catch(Exception e){
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        params.put("moduleTable", moduleTable2);
        params.put("entity", new LogsticsPatternDetails()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
        params.put("toolBarWidth", 0);//操作区
        params.put("checkBox", "yes");
        params.put("getFieldAttributesType", "pageingrid");//pageingrid：网格字段
        String type = params .get("type").toString();
        if ("1".equals(type)){
            params.put("readOnly", false);//生成列是否可编辑
            mv.addObject("enableEdit", 1); //当前页面是否可编辑（0：不可编辑，1：可编辑）
        } else {
            params.put("readOnly", true);//生成列是否可编辑
            mv.addObject("enableEdit", 0); //当前页面是否可编辑（0：不可编辑，1：可编辑）
        }
        mv.addObject("gridColumns", gridColumnsPropertyModel.queryGridColumnsPropertyModel(params));
        params.put("moduleTable", moduleTable3);
        params.put("entity", new LogisticsMmodeGrads());
        params.put("toolBarWidth", 0);//操作
        params.put("checkBox", "yes");
        params.put("getFieldAttributesType", "pageingrid");//pageingrid：网格字段// 区
        Map<String, Object> stringObjectMap = gridColumnsPropertyModel.queryGridColumnsPropertyModel(params);
        mv.addObject("gridColumnsZJ", stringObjectMap);
        mv.addObject("gridColumnsJZ", stringObjectMap);
        mv.addObject("ajaxResult", ajaxResult); //查询结果状态
        mv.addObject("fieldRequiredList", fieldRequiredList); //必填字段
        mv.addObject("fieldsList", fieldsList); //生成控件
        mv.addObject("fieldsHiddenList", fieldsHiddenList); //隐藏的表头
        mv.addObject("type",type); //当前页面是否可编辑（0：不可编辑，1：可编辑）
        mv.setViewName(prefix + "/logsticspattern_edit");
        return mv;
    }

    /**
     * 修改物流名称
     * @author fxz
     * @date: 2022-09-22
     */
    @RequiresPermissions("business:logsticspattern:edit")
    @Log(title = "修改物流名称信息", businessType = BusinessType.UPDATE)
    @PostMapping("/editpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult editpost(@RequestParam Map<String, Object> params) {


        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= logsticsPatternService.updateLogsticsPattern(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 删除物流名称
     * @author fxz
     * @date: 2022-09-22
     */
    @RequiresPermissions("business:logsticspattern:edit")
    @Log(title = "删除物流名称", businessType = BusinessType.DELETE)
    @PostMapping("/deletepost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult deletepost(@RequestParam Map<String, Object> params) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= logsticsPatternService.deleteLogsticspattern(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 同步材质
     * @author fxz
     * @date: 2023-02-27
     */
    @RequiresPermissions("business:logsticspattern:edit")
    @Log(title = "同步材质", businessType = BusinessType.UPDATE)
    @PostMapping("/hotMaterial")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult hotMaterial(@RequestParam Map<String, Object> params) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= logsticsPatternService.hotMaterial(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * @Description: 打开选择列表
     * @Param: [params]
     * @return: org.springframework.web.servlet.ModelAndView
     * @Author: hlf
     * @date: 2022-08-15 15:42
     */
    @GetMapping("/select")
    public ModelAndView selectList(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        params.put("entity", new LogsticsPattern()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
        params.put("toolBarWidth", 0);
        if (params.get("pagetype") != null && params.get("pagetype").toString().equalsIgnoreCase("checkbox"))
            params.put("checkBox", "yes");
        else params.put("radio", "yes");
        ModelAndView mv = this.getModelAndView();
        AjaxResult ajaxResult = new AjaxResult();
        Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();

        mv.addObject("fields", TypeUtils.mapToJson(dictionaryForFieldMap));
        mv.addObject("ajaxResult", ajaxResult);
        mv.addObject("gridColumns", gridColumnsPropertyModel.queryGridColumnsPropertyModel(params));
        mv.addObject("prefix", prefix);
        mv.addObject("moduleTable", moduleTable);
        mv.setViewName("common/select");
        return mv;
    }
}
